package org.jboss.tools.examples.data;

import org.jboss.tools.examples.model.Calendario;


import java.util.List;
import javax.annotation.PostConstruct;
import javax.enterprise.context.RequestScoped;
import javax.enterprise.event.Observes;
import javax.enterprise.event.Reception;

import javax.enterprise.inject.Produces;
import javax.inject.Inject;
import javax.inject.Named;
import javax.persistence.EntityManager;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;

@RequestScoped
public class CalendarioListProducer {
	@Inject
	private EntityManager em;

	private List<Calendario> appuntamenti;

	// @Named provides access the return value via the EL variable name "members" in the UI (e.g.,
	// Facelets or JSP view)
	@Produces
	@Named
	public List<Calendario> getAppuntamenti() {
		return appuntamenti;
	}

	public void onCalendarioListChanged(@Observes(notifyObserver = Reception.IF_EXISTS) final Calendario member) {
		retrieveAllCalendariosOrderedByName();
	}

	@PostConstruct
	public void retrieveAllCalendariosOrderedByName() {
		CriteriaBuilder cb = em.getCriteriaBuilder();
		CriteriaQuery<Calendario> criteria = cb.createQuery(Calendario.class);
		Root<Calendario> member = criteria.from(Calendario.class);
		// Swap criteria statements if you would like to try out type-safe criteria queries, a new
		// feature in JPA 2.0
		// criteria.select(member).orderBy(cb.asc(member.get(Calendario_.name)));
		criteria.select(member).orderBy(cb.asc(member.get("data")));
		appuntamenti = em.createQuery(criteria).getResultList();
	}
}
